package com.hyt.it.ogt.kq.service.bm.service.impl;

import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.core.base.BaseEntity;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.core.httpclient.FormFieldKeyValuePair;
import com.hyt.it.ogt.kq.common.bm.utils.Constant;
import com.hyt.it.ogt.kq.service.bm.mapper.ProjectMapper;
import com.hyt.it.ogt.kq.service.bm.mapper.ProjectSubjectMapper;
import com.hyt.it.ogt.kq.service.bm.mapper.StudentInfoMapper;
import com.hyt.it.ogt.kq.service.bm.mapper.StudentSubjectMapper;
import com.hyt.it.ogt.kq.service.bm.model.entity.Project;
import com.hyt.it.ogt.kq.service.bm.model.entity.ProjectSubject;
import com.hyt.it.ogt.kq.service.bm.model.entity.StudentSubject;
import com.hyt.it.ogt.kq.service.bm.model.vo.StudentInfoVo;
import com.hyt.it.ogt.kq.service.bm.model.vo.SubjectStatVo;
import com.hyt.it.ogt.kq.service.bm.service.*;
import com.hyt.it.ogt.kq.service.gov.api.bm.BmApi;
import com.hyt.loginfo.service.IBaseLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 报名项目科目 服务实现类
 * </p>
 *
 * @author wangt
 * @since 2020-05-15
 */
@Slf4j
@Service
public class ProjectSubjectServiceImpl extends BaseServiceImpl<ProjectSubjectMapper, ProjectSubject> implements IProjectSubjectService {

    @Resource
    ProjectSubjectMapper projectSubjectMapper;
    @Resource
    StudentSubjectMapper studentSubjectMapper;
    @Resource
    StudentInfoMapper studentInfoMapper;
    @Autowired
    IProjectExamService iProjectExamService;
    @Autowired
    IStudentSubjectService iStudentSubjectServiceService;
    @Autowired
    ISubjectExamService iSubjectExamServiceService;
    @Resource
    BmApi kwGovClient;
    @Resource
    private IUserPermissionService iUserPermissionService;
    @Resource
    private IBaseLoginService iBaseLoginService;
    @Resource
    private ProjectMapper projectMapper;

    /**
     * @Params:
     * @Description: 编辑报名项目科目数据
     * @Author: STARF
     * @CreateDate: 2022/3/10 11:33
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object update(ProjectSubject projectSubject) throws Exception {
        List<ProjectSubject> list = this.querySubjectList(projectSubject.getProjectId(), projectSubject.getSubjectName());
        boolean flag = true;
        if (CollectionUtils.isNotEmpty(list)) {
            for (ProjectSubject subject : list) {
                if (!subject.getSubjectId().equals(projectSubject.getId())) {
                    flag = false;
                    break;
                }
            }
        }
        if (!flag) {
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010134).build();
        }

        //项目免费时，科目不可设为缴费
        Project project = projectMapper.selectById(projectSubject.getProjectId());
        if (null == project) {
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010134).build();
        }
        if (0 == project.getIsPay() && 1 == projectSubject.getIsPay()) {
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010108).build();
        }

        List<String> permissionList = iUserPermissionService.queryPermissionByUserId(project.getId(), iBaseLoginService.getUserId());
        String deptId = "";
        if (0 == project.getIsOpen()) {
            deptId = iBaseLoginService.getDeptId();
        }
        List<SubjectStatVo> subjectList = projectSubjectMapper.statSubjectByProjectId(project.getId(), permissionList, projectSubject.getSubjectId(), deptId);
        if (subjectList != null && subjectList.isEmpty()) {
            subjectList = new ArrayList<>();
            SubjectStatVo tempVo = new SubjectStatVo();
            BeanUtils.copyProperties(projectSubject, tempVo);
            tempVo.setApplyNum(0);
            tempVo.setAuditNum(0);
            tempVo.setPayNum(0);
            tempVo.setArrangeNum(0);
            subjectList.add(tempVo);
        }
        if (null != subjectList) {
            if (subjectList.get(0).getApplyNum() > 0) {
                return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010105).data(project).build();
            }
        }

        if (projectSubject.getIsPay() == 0) {
            projectSubject.setPrice(null);
        }

        this.updateProject(projectSubject);
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(projectSubject).build();
    }

    /**
     * 统计项目所有科目报名信息
     *
     * @param projectId
     * @param permissionList
     * @param subjectId
     * @param deptId
     * @return
     */
    @Override
    public List<SubjectStatVo> statSubjectByProjectId(String projectId, List<String> permissionList, String subjectId, String deptId) {
        List<SubjectStatVo> subjectList = projectSubjectMapper.statSubjectByProjectId(projectId, permissionList, subjectId, deptId);
        if (CollectionUtils.isEmpty(subjectList)) {
            subjectList = new ArrayList<SubjectStatVo>();
            ProjectSubject projectSubject = this.queryBySubjectId(projectId, subjectId);
            SubjectStatVo tempVo = new SubjectStatVo();
            BeanUtils.copyProperties(projectSubject, tempVo);
            tempVo.setApplyNum(0);
            tempVo.setAuditNum(0);
            tempVo.setPayNum(0);
            tempVo.setArrangeNum(0);
            if (null == tempVo.getPrice() || tempVo.getIsPay() == 0) {
                tempVo.setPrice(BigDecimal.ZERO);
            }
            subjectList.add(tempVo);
        } else {
            for (SubjectStatVo subjectStatVo : subjectList) {
                if (null == subjectStatVo.getPrice() || subjectStatVo.getIsPay() == 0) {
                    subjectStatVo.setPrice(BigDecimal.ZERO);
                }
            }
        }
        return subjectList;
    }

    /**
     * 删除科目
     *
     * @param id
     * @param projectId
     * @param subjectId
     * @throws Exception
     */
    @Override
    public void deleteSubject(String id, String projectId, String subjectId) throws Exception {
        this.removeById(id);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("project_id", projectId);
        map.put("subject_id", subjectId);
        iStudentSubjectServiceService.removeByMap(map);
        iSubjectExamServiceService.removeByMap(map);
    }

    /**
     * @Params:
     * @Description: 删除项目所有科目
     * @Author: STARF
     * @CreateDate: 2022/3/17 11:04
     **/
    @Override
    public void deleteSubjectByProjectId(String projectId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("project_id", projectId);
        iStudentSubjectServiceService.removeByMap(map);
        iSubjectExamServiceService.removeByMap(map);
    }

    @Override
    public List<Map<String, String>> getSubjectList(String enrollId, String subjectId) {

        return projectSubjectMapper.getSubjectListByProjcetId(enrollId, subjectId);
    }

    @Override
    public List<Map<String, Object>> getProjectCollectInfos(String enrollId, String subjectId,
                                                            List<String> candidateIds, Boolean isAll, String kwFlag) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        ProjectSubject projectSubject = projectSubjectMapper.queryBySubjectId(enrollId, subjectId);
        String payState = projectSubject.getIsPay() == 1 ? "1" : "";
        // 查询科目下报名的考生（考务未导入）
        List<StudentSubject> list1 = new ArrayList<StudentSubject>();
        if (!isAll) { // all是 false的话 过滤下 包含 List<String> CandidateIds这些id的考生
            list1 = studentSubjectMapper.getStudentSubjectList(enrollId, subjectId, candidateIds, payState, kwFlag);
        } else {
            list1 = studentSubjectMapper.getStudentSubjectList(enrollId, subjectId, null, payState, kwFlag);
        }
        for (int i = 0; i < list1.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            String studentId = list1.get(i).getStudentId();
            map.put("CandidateId", studentId);
            List<StudentInfoVo> sList = studentInfoMapper.getByStudentId(enrollId, studentId, "1");
            // 循环考生信息
            List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
            if (sList != null) {
                for (int j = 0; j < sList.size(); j++) {
                    Map<String, Object> projectCollectInfos = new HashMap<>();
                    projectCollectInfos.put("projectCollectInfoId",
                            sList.get(j).getProjectCollectInfoId());
                    projectCollectInfos.put("projectCollectInfoValue", sList.get(j).getValue());
                    projectCollectInfos.put("componentName", sList.get(j).getComponentName());
                    projectCollectInfos.put("title", sList.get(j).getProjectCollectInfoName());
                    list2.add(projectCollectInfos);
                }
            }

            map.put("projectCollectInfos", list2);

            if (sList != null && sList.size() > 0) {
                list.add(map);
            }
        }
        return list;
    }

    @Override
    public void recordSuccessCandidates(String enrollId, String subjectId, List<String> studentIds) {
        studentInfoMapper.updateKwFlag(enrollId, subjectId, studentIds);
    }

    @Override
    public void updateProject(ProjectSubject projectSubject) {
        projectSubjectMapper.updateProject(projectSubject);
    }

    @Override
    public ProjectSubject querySubject(String id) {
        return projectSubjectMapper.querySubject(id);
    }

    @Override
    public List<ProjectSubject> querySubjectList(String projectId, String subjectName) {
        return projectSubjectMapper.querySubjectList(projectId, subjectName);
    }

    @Override
    public ProjectSubject querySubjectByName(String projectId, String subjectName) {
        return projectSubjectMapper.querySubjectByName(projectId, subjectName);
    }

    @Override
    public void updateSubject(String projectId, String subjectId) {
        studentInfoMapper.updateSubjectKwFlag(projectId, subjectId);
    }

    @Override
    public String getSqlColumn(String projectId) {
        return projectSubjectMapper.getSqlColumn(projectId);
    }

    @Override
    public List<Map<String, Object>> queryAllStudent(String columns, String projectId, String studentId, String isPay, String isAudit) {
        return projectSubjectMapper.queryAllStudent(columns, projectId, studentId, isPay, isAudit);
    }

    @Override
    public List<Map<String, Object>> queryStudentById(String columns, String projectId, String studentId) {
        return projectSubjectMapper.queryStudentById(columns, projectId, studentId);
    }

    @Override
    public ProjectSubject queryBySubjectId(String projectId, String subjectId) {
        return projectSubjectMapper.queryBySubjectId(projectId, subjectId);
    }

    @Override
    public ProjectSubject queryBySubjectId(String subjectId) {
        return this.lambdaQuery()
                .eq(ProjectSubject::getSubjectId, subjectId)
                .eq(BaseEntity::getDelFlag, Boolean.FALSE)
                .last(LIMIT_1)
                .one();
    }

    @Override
    public List<Map<String, Object>> queryAllStudent(String columns, String projectId, String studentId, String isPay, String isAudit, int pageNo, int pageSize) {
        return projectSubjectMapper.queryAllStudentByPage(columns, projectId, studentId, isPay, isAudit, pageNo, pageSize);
    }

    @Override
    public Integer getCurrentRegSubjectCount(String projectId, String subjectId) {
        // 获取当前科目的报考人数
        Integer count = studentSubjectMapper.countStudentSubject(projectId, subjectId);
        return null == count ? Integer.valueOf(0) : count;
    }

    /**
     * 根据项目id查询科目列表
     *
     * @see com.hyt.it.ogt.kq.service.bm.service.IProjectSubjectService#getProjectSubjectsByProjectId(java.lang.String)
     **/
    @Override
    public List<ProjectSubject> getProjectSubjectsByProjectId(String projectId) {
        return projectSubjectMapper.querySubjectList(projectId, null);
    }

    @Override
    public List<FormFieldKeyValuePair> selectSubject(String projectId) {
        List<ProjectSubject> projectSubjectList = getProjectSubjectsByProjectId(projectId);
        List<FormFieldKeyValuePair> keyValuePairs = projectSubjectList.stream()
                .map(projectSubject -> new FormFieldKeyValuePair(projectSubject.getSubjectId(), projectSubject.getSubjectName()))
                .collect(Collectors.toList());
        return keyValuePairs;
    }
}
